<template>
  <div class="exam-container" :style="containerStyle">
    <el-card class="exam-card">
      <template #header>
        <div class="exam-header">
        <h2>{{ examInfo.name }}</h2>
        <div class="exam-info">
          <span>总分：{{ examInfo.totalScore }}分</span>
          <span>时长：{{ examInfo.duration }}分钟</span>
          <!-- 移除剩余时间显示 -->
        </div>
      </div>
      </template>
      
      <div class="exam-content">
        <!-- 题目列表区 -->
        <div class="questions-container">
          <!-- 题目导航栏 -->
          <div class="question-nav">
            <div class="nav-title">题目导航</div>
            <div class="nav-list">
              <el-button 
                v-for="(question, index) in questions" 
                :key="question.id"
                :class="['nav-item', { 'active': currentQuestionIndex === index, 'answered': isQuestionAnswered(index) }]"
                @click="jumpToQuestion(index)"
                size="small"
              >
                {{ index + 1 }}
              </el-button>
            </div>
          </div>
          
          <!-- 题目详情区 -->
          <div class="question-detail">
            <div 
              v-for="(question, index) in questions" 
              :key="question.id" 
              :class="['question-section', { 'active': currentQuestionIndex === index }]"
            >
              <h3>{{ getQuestionTypeLabelById(question.typeId) }}（{{ question.score }}分）</h3>
            <p class="question-content">{{ index + 1 }}. {{ question.content }}</p>
              
              <!-- 单选题 -->
              <div v-if="question.type === 'single'" class="options">
                <el-radio-group v-model="answers[question.id]" class="radio-group">
                  <el-radio 
                    v-for="(option, optIndex) in question.options" 
                    :key="optIndex" 
                    :label="option.value"
                    class="radio-option"
                  >
                    {{ option.label }}. {{ option.text }}
                  </el-radio>
                </el-radio-group>
              </div>
              
              <!-- 多选题 -->
              <div v-else-if="question.type === 'multiple'" class="options">
                <el-checkbox-group v-model="answers[question.id]" class="checkbox-group">
                  <el-checkbox 
                    v-for="(option, optIndex) in question.options" 
                    :key="optIndex" 
                    :label="option.value"
                    class="checkbox-option"
                  >
                    {{ option.label }}. {{ option.text }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              
              <!-- 判断题 -->
              <div v-else-if="question.type === 'trueFalse'" class="options">
                <el-radio-group v-model="answers[question.id]" class="radio-group">
                  <el-radio 
                    v-for="(option, optIndex) in question.options" 
                    :key="optIndex" 
                    :label="option.value"
                    class="radio-option"
                  >
                    {{ option.label }}. {{ option.text }}
                  </el-radio>
                </el-radio-group>
              </div>
              
              <!-- 填空题 -->
              <div v-else-if="question.type === 'fill'" class="fill-blank">
                <el-input 
                  v-model="answers[question.id]" 
                  placeholder="请输入答案" 
                  class="fill-input"
                />
              </div>
              
              <!-- 简答题 -->
              <div v-else-if="question.type === 'short'" class="short-answer">
                <el-input 
                  v-model="answers[question.id]" 
                  type="textarea" 
                  :rows="6" 
                  placeholder="请输入答案" 
                  class="short-input"
                />
              </div>
              
              <!-- 题目导航按钮 -->
              <div class="question-navigation">
                <el-button 
                  v-if="index > 0" 
                  @click="previousQuestion" 
                  icon="ArrowLeft"
                >
                  上一题
                </el-button>
                <el-button 
                  v-if="index < questions.length - 1" 
                  @click="nextQuestion" 
                  icon-position="right"
                  icon="ArrowRight"
                >
                  下一题
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="exam-footer">
          <el-button type="primary" @click="submitExam">提交试卷</el-button>
          <el-button type="warning" @click="saveProgress">保存进度</el-button>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount, onUpdated } from 'vue'
import { getStudentExams, type ExamStudentVo } from '@/services/examService'
import { get, post } from '@/utils/api'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 考试列表数据
const examList = ref<ExamStudentVo[]>([])
const loading = ref(true)

// 考试信息
const examInfo = reactive({
  examId: 0, // 添加examId字段
  name: '',
  duration: 0,
  totalScore: 0
})

// 考试详情数据结构
interface Question {
  score: number
  typeId: number
  questionContent: string
  optionA: string | null
  optionB: string | null
  optionC: string | null
  optionD: string | null
  correctAnswer: string
  difficulty: string
  questionId: number
}

interface ExamDetail {
  examId: number
  examName: string
  courseId: number
  courseName: string
  startTime: string
  endTime: string
  totalScore: number
  examDuration: number | null
  description: string
  status: number
  questionList: Question[]
}

// 获取学生考试列表
const fetchStudentExams = async () => {
  try {
    loading.value = true
    const response = await getStudentExams()
    if (response.code === 200) {
      examList.value = response.data
      // 如果需要，可以在这里设置默认选中的考试
      // 或者跳转到考试列表页面
    } else {
      ElMessage.error(response.msg || '获取考试列表失败')
    }
  } catch (error) {
    ElMessage.error('获取考试列表失败')
  } finally {
    loading.value = false
  }
}

// 页面尺寸相关
const appWidth = ref(0)
const appHeight = ref(0)

// 获取#app容器的尺寸
const getAppContainerSize = () => {
  const appContainer = document.getElementById('app')
  if (appContainer) {
    appWidth.value = appContainer.offsetWidth
    appHeight.value = appContainer.offsetHeight
  }
}

// 当前题目索引
const currentQuestionIndex = ref(0)

// 倒计时相关
const timeLeft = ref('90:00')
let timer: any = null

// 题目数据
const questions = ref<any[]>([])

// 学生答案
const answers = reactive<Record<number, any>>({})

// 根据后端数据转换题目格式
const transformQuestions = (examDetail: ExamDetail) => {
  return examDetail.questionList.map((question, index) => {
    const transformedQuestion: any = {
      id: question.questionId, // 使用后端返回的questionId
      typeId: question.typeId,
      content: question.questionContent,
      score: question.score
    }
    
    // 根据typeId设置题目类型
    switch (question.typeId) {
      case 1: // 单选题
        transformedQuestion.type = 'single'
        break
      case 2: // 多选题
        transformedQuestion.type = 'multiple'
        break
      case 3: // 判断题
        transformedQuestion.type = 'trueFalse'
        break
      case 4: // 填空题
        transformedQuestion.type = 'fill'
        break
      default:
        transformedQuestion.type = 'single' // 默认为单选题
    }
    
    // 为选择题添加选项
    if (question.typeId === 1 || question.typeId === 2 || question.typeId === 3) {
      transformedQuestion.options = []
      if (question.typeId === 3) {
        // 判断题选项
        transformedQuestion.options.push({ label: 'A', value: 'A', text: '正确' })
        transformedQuestion.options.push({ label: 'B', value: 'B', text: '错误' })
      } else {
        // 单选题和多选题选项
        if (question.optionA) {
          transformedQuestion.options.push({ label: 'A', value: 'A', text: question.optionA })
        }
        if (question.optionB) {
          transformedQuestion.options.push({ label: 'B', value: 'B', text: question.optionB })
        }
        if (question.optionC) {
          transformedQuestion.options.push({ label: 'C', value: 'C', text: question.optionC })
        }
        if (question.optionD) {
          transformedQuestion.options.push({ label: 'D', value: 'D', text: question.optionD })
        }
      }
    }
    
    // 初始化答案
    if (question.typeId === 2) {
      // 多选题答案初始化为空数组
      answers[question.questionId] = []
    } else {
      // 其他题目答案初始化为空字符串
      answers[question.questionId] = ''
    }
    
    return transformedQuestion
  })
}

// 获取考试详情
const fetchExamDetail = async (examId: string) => {
  try {
    loading.value = true
    const response = await get(`/exam/query/exStId?examId=${examId}`)
    if (response.code === 200) {
      const examDetail: ExamDetail = response.data
      
      // 设置考试信息
      examInfo.examId = examDetail.examId // 设置examId
      examInfo.name = examDetail.examName
      examInfo.totalScore = examDetail.totalScore
      examInfo.duration = examDetail.examDuration || 0
      
      // 转换题目数据
      questions.value = transformQuestions(examDetail)
      
      // 初始化倒计时
      timeLeft.value = `${examInfo.duration}:00`
      
      // 记录考试开始时间
      try {
        await post(`/student-exam/record/enter?examId=${examDetail.examId}`, {})
      } catch (error) {
        console.error('记录考试开始时间失败:', error)
      }
      
      // 获取考生该考试的答题情况
      try {
        const progressResponse = await get(`/student-exam/query/student?examId=${examDetail.examId}`)
        if (progressResponse.code === 200 && progressResponse.data) {
          const { questionVo } = progressResponse.data
          // 填充答题情况
          questionVo.forEach((item: any) => {
            if (answers[item.questionId] !== undefined) {
              if (Array.isArray(answers[item.questionId])) {
                // 多选题答案处理
                answers[item.questionId] = item.answer.split('')
              } else {
                // 单选题和判断题答案处理
                answers[item.questionId] = item.answer
              }
            }
          })
        }
      } catch (error) {
        console.error('获取答题情况失败:', error)
      }
    } else {
      ElMessage.error(response.msg || '获取考试详情失败')
    }
  } catch (error) {
    ElMessage.error('获取考试详情失败')
  } finally {
    loading.value = false
  }
}

// 获取题目类型标签
const getQuestionTypeLabel = (type: string) => {
  switch (type) {
    case 'single': return '单选题'
    case 'multiple': return '多选题'
    case 'trueFalse': return '判断题'
    case 'fill': return '填空题'
    case 'short': return '简答题'
    default: return '未知题型'
  }
}

// 根据typeId获取题目类型标签
const getQuestionTypeLabelById = (typeId: number) => {
  switch (typeId) {
    case 1: return '单选题'
    case 2: return '多选题'
    case 3: return '判断题'
    case 4: return '填空题'
    default: return '未知题型'
  }
}

// 计算容器样式
const containerStyle = computed(() => {
  return {
    width: appWidth.value ? `${appWidth.value}px` : '100%',
    height: appHeight.value ? `${appHeight.value}px` : '100%'
  }
})

// 跳转到指定题目
const jumpToQuestion = (index: number) => {
  currentQuestionIndex.value = index
}

// 检查题目是否已答题
const isQuestionAnswered = (index: number) => {
  const question = questions.value[index]
  if (!question) return false
  
  const answer = answers[question.id]
  if (answer === undefined || answer === null) return false
  
  // 对于多选题，检查数组是否非空
  if (Array.isArray(answer)) {
    return answer.length > 0
  }
  
  // 对于其他题型，检查是否非空字符串
  return answer !== ''
}

// 上一题
const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

// 下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++
  }
}

// 保存进度
const saveProgress = async () => {
  try {
    // 构造要发送的数据
    const saveData: any = {
      examId: examInfo.examId,
      questionVo: []
    }
    
    // 遍历所有题目，收集答题情况
    questions.value.forEach((question: any) => {
      const answer = answers[question.id]
      if (answer !== undefined && answer !== null && answer !== '') {
        // 格式化答案
        let formattedAnswer = ''
        if (Array.isArray(answer)) {
          // 多选题答案按顺序排列
          formattedAnswer = answer.sort().join('')
        } else {
          // 单选题和判断题答案直接使用
          formattedAnswer = answer
        }
        
        saveData.questionVo.push({
          answer: formattedAnswer,
          questionId: question.id
        })
      }
    })
    
    // 发送保存进度请求
    const response = await post('/student-exam/save/student', saveData)
    if (response.code === 200) {
      ElMessage.success('进度保存成功')
    } else {
      ElMessage.error(response.msg || '保存进度失败')
    }
  } catch (error) {
    ElMessage.error('保存进度失败')
  }
}

// 启动倒计时
const startTimer = () => {
  let totalSeconds = examInfo.duration * 60
  
  timer = setInterval(() => {
    totalSeconds--
    const minutes = Math.floor(totalSeconds / 60)
    const seconds = totalSeconds % 60
    timeLeft.value = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    
    if (totalSeconds <= 0) {
      clearInterval(timer)
      ElMessage.warning('考试时间已结束，正在自动提交试卷...')
      submitExam()
    } else if (totalSeconds <= 300) { // 剩余5分钟提醒
      ElMessage.warning(`考试即将结束，剩余时间：${timeLeft.value}`)
    }
  }, 1000)
}

// 提交试卷
const submitExam = () => {
  ElMessageBox.confirm('确定要提交试卷吗？提交后无法修改。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 构造要发送的数据
      const submitData: any = {
        examId: examInfo.examId,
        questionVo: []
      }
      
      // 遍历所有题目，收集答题情况
      questions.value.forEach((question: any) => {
        const answer = answers[question.id]
        if (answer !== undefined && answer !== null && answer !== '') {
          // 格式化答案
          let formattedAnswer = ''
          if (Array.isArray(answer)) {
            // 多选题答案按顺序排列
            formattedAnswer = answer.sort().join('')
          } else {
            // 单选题和判断题答案直接使用
            formattedAnswer = answer
          }
          
          submitData.questionVo.push({
            answer: formattedAnswer,
            questionId: question.id
          })
        }
      })
      
      // 发送提交试卷请求
      const response = await post('/student-exam/submit', submitData)
      if (response.code === 200) {
        ElMessage.success('试卷提交成功！')
        router.push('/student/my-exams')
      } else {
        ElMessage.error(response.msg || '提交试卷失败')
      }
    } catch (error) {
      ElMessage.error('提交试卷失败')
    }
  }).catch(() => {
    // 取消操作
  })
}



// 组件挂载时启动计时器并获取尺寸
onMounted(() => {
  const examId = route.params.id as string
  if (examId) {
    fetchExamDetail(examId)
  } else {
    ElMessage.error('缺少考试ID参数')
    router.back()
  }
  // startTimer() // 移除启动倒计时的代码
  getAppContainerSize()
  fetchStudentExams() // 获取学生考试列表
  
  // 添加窗口大小变化监听器
  window.addEventListener('resize', getAppContainerSize)
})

// 组件更新时也获取尺寸
onUpdated(() => {
  getAppContainerSize()
})

// 组件卸载前清除计时器和事件监听器
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
  window.removeEventListener('resize', getAppContainerSize)
})
</script>

<style scoped>
.exam-container {
  padding: 0;
  background-color: #fff;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  margin: 0;
}

/* 动态尺寸样式将通过JavaScript应用 */

.exam-card {
  margin-top: 10px;
  width: 95%;
  height: 80%;
  margin: 0;
  border-radius: 0;
  display: flex;
  flex-direction: column;
}

.exam-header h2 {
  margin: 0;
  color: #333;
}

.exam-info {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.time-left {
  font-weight: bold;
  color: #f56c6c;
}

.exam-content {
  flex: 1;
  overflow: hidden;
}

.questions-container {
  display: flex;
  height: 100%;
  gap: 20px;
  padding: 20px 0;
}

.question-nav {
  width: 200px;
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100% - 40px);
  overflow-y: auto;
}

.nav-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.nav-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.nav-item {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  padding: 0;
}

.nav-item.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.nav-item.answered {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.question-detail {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  height: 100%;
}

.question-section {
  display: none;
}

.question-section.active {
  display: block;
}

.question-content {
  font-weight: 500;
  margin: 15px 0;
  line-height: 1.6;
}

.radio-group, .checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 15px;
}

.radio-option, .checkbox-option {
  margin-right: 0;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
}

.radio-option:hover, .checkbox-option:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.fill-input, .short-input {
  width: 100%;
  margin-top: 10px;
}

.short-input {
  max-width: 100%;
}

.question-navigation {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.exam-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px 0;
  margin: 0;
  border-top: 1px solid #eee;
}
</style>